package com.supermarket.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.supermarket.entity.Role;
import com.supermarket.entity.User;
import com.supermarket.mapper.RoleMapper;
import com.supermarket.mapper.UserMapper;
import com.supermarket.service.UserService;
import com.supermarket.util.PasswordUtil;
import com.supermarket.util.R;
import com.supermarket.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User getById(Long id) {
        User user = userMapper.selectById(id);
        Role role = roleMapper.selectById(user.getUserRole());
        user.setRoleName(role.getRoleName());
        return user;
    }

    @Override
    public User getByUserCode(String userCode) {
        return userMapper.getByUserCode(userCode);
    }

    @Override
    public List<User> getAll() {
        return userMapper.selectAll();
    }

    @Override
    public void create(User user) {
        // 1. 生成盐值
        String salt = PasswordUtil.salt();
        user.setSalt(salt);
        
        // 2. 加密密码
        String plainPassword = user.getUserPassword();
        if (plainPassword != null) {
            String encryptedPassword = PasswordUtil.encode(plainPassword, salt);
            user.setUserPassword(encryptedPassword);
        }
        
        // 3. 设置默认头像
        if (user.getHeadUrl() == null || user.getHeadUrl().isEmpty()) {
            user.setHeadUrl("img/face.png");
        }
        
        // 4. 插入数据库
        userMapper.insert(user);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public User login(String userCode, String passWord) {
        User user = userMapper.getByUserCode(userCode);

        //判断用户名对应的用户是否存在
        if(null != user){
            System.out.println(user);
            System.out.println(user.getRole());
            //验证用户对应的密码是否正确
            if(PasswordUtil.match(passWord,user.getUserPassword())){
                //脱敏处理
                user.setUserPassword(null);
                user.setSalt(null);
                return user;
            }
        }
        return null;
    }

    @Override
    public void updateUserImage(Long id, String headUrl) {
        if (id == null || !StringUtils.hasText(headUrl)) return;
        User user = userMapper.selectById(id);
        if (user != null) {
            user.setHeadUrl(headUrl);
            userMapper.update(user);
        }
    }
    
    @Override
    public R<Object> getUserList(Integer currentPage, Integer pageSize, String userCode, String userName) {
        try {
            // 分页参数
            int start = (currentPage - 1) * pageSize;
            
            // 用户列表
            List<User> userList = userMapper.getUserList(start, pageSize, userCode, userName);
            
            // 总记录数
            int totalCount = userMapper.getUserCount(userCode, userName);
            
            // 返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("list", userList);
            data.put("currentPage", currentPage);
            data.put("pageSize", pageSize);
            data.put("totalCount", totalCount);
            
            return R.createSuccess(data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.createError(StatusCode.ERROR, "查询失败：" + e.getMessage());
        }
    }
    
    @Override
    public R<String> updatePassword(Long userId, String oldPassword, String newPassword) {
        try {
            // 1. 根据用户ID获取用户信息
            User user = userMapper.selectById(userId);
            if (user == null) {
                return R.createError(StatusCode.ERROR, "用户不存在");
            }
            
            // 2. 验证旧密码是否正确
            if (!PasswordUtil.match(oldPassword, user.getUserPassword())) {
                return R.createError(StatusCode.ERROR, "旧密码不正确");
            }
            
            // 3. 加密新密码
            String encodedNewPassword = PasswordUtil.encodeDefaultSalt(newPassword);
            
            // 4. 更新密码
            user.setUserPassword(encodedNewPassword);
            int result = userMapper.update(user);
            
            if (result > 0) {
                return R.createSuccess("密码修改成功");
            } else {
                return R.createError(StatusCode.ERROR, "密码修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.createError(StatusCode.ERROR, "密码修改异常：" + e.getMessage());
        }
    }
}
